<template>
  <basic-container>
    <avue-crud
      :option="options"
      v-model:search="search"
      v-model:page="page"
      v-model="form"
      :table-loading="loading"
      :data="data"
      :permission="permissionList"
      :before-open="beforeOpen"
      ref="crud"
      @row-update="rowUpdate"
      @row-save="rowSave"
      @row-del="rowDel"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @on-load="onLoad"
    >
      <template #menu-left>
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          v-if="permission.trial_add"
          @click="handleMenu(1)"
          >新 增</el-button
        >
        <el-button
          type="danger"
          icon="el-icon-delete"
          plain
          v-if="permission.trial_delete"
          @click="handleDelete"
          >删 除
        </el-button>
        <!-- <el-button type="warning" plain icon="el-icon-download" @click="handleExport"
          >导 出
        </el-button> -->
      </template>
      <template #name="{ row, index }">
        <span style="color: #72afd2; cursor: pointer" @click="handleMenu(2, row, index)">{{
          row.name
        }}</span>
      </template>
      <template #RZCJ="{ row }">
        <div class="flex gap-2">
<!--          <el-tag
            type="primary"
            effect="light"
            style="margin-right: 5px; cursor: pointer"
            @click="handleMenu(3, row)"
            >新建码</el-tag
          >-->
          <el-tag type="success" effect="light" style="cursor: pointer" @click="handleMenu(4, row)"
            >入组采集</el-tag
          >
        </div>
      </template>
      <template #JDTJ="{ row }">
        <div class="flex gap-2">
          <el-tag type="primary" effect="light" style="cursor: pointer" @click="handleMenu(5, row)"
            >查看统计</el-tag
          >
        </div>
      </template>
    </avue-crud>
    <el-dialog v-model="isQRCode" title="新建码" width="500" body-class="QR-code-dialog-body">
      <div class="QR-code-content">
        <div class="QR-code-corm">
          <el-row :gutter="20">
            <el-col :span="12" style="display: flex">
              <span style="line-height: 32px">选择分组：</span>
              <el-col :span="16">
                <el-select
                  v-model="QRCodeForm.groupValue"
                  placeholder="请选择分组"
                  @change="changeQRCodeSelect"
                >
                  <el-option
                    v-for="item in groupOption"
                    :key="item.value"
                    :label="item.name"
                    :value="item.id"
                  />
                </el-select>
              </el-col>
            </el-col>
            <el-col :span="12" style="display: flex">
              <span style="line-height: 32px">选择模式：</span>
              <el-col :span="16">
                <el-select
                  v-model="QRCodeForm.patternValue"
                  placeholder="请选择模式"
                  @change="changeQRCodeSelect"
                >
                  <el-option
                    v-for="item in patternOption"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-col>
            </el-col>
          </el-row>
        </div>
        <div class="QR-code-img">
          <canvas id="qrcode"></canvas>
          <a :href="QRCodeUrl" target="_blank" style="color: #3c8dbc">点击进入</a>
        </div>
        <div class="QR-code-bottom">
          <!--  <el-input
             v-model="QRCodeForm.checkCode"
             type="password"
             style="width: 200px; margin-right: 50px; flex: 1"
             placeholder=""
           >
            <template #prepend>
               校验码
               <InfoFilled style="width: 16px; height: 16px" />
             </template>
             <template #append><Refresh style="width: 16px; height: 16px" /></template>
          </el-input>-->
          <div  style="width: 200px; margin-right: 50px; flex: 1"></div>
          <el-button type="primary" @click="handleCopyQRCodeUrl"> 复制链接 </el-button>
          <el-button @click="isQRCode = false">关闭</el-button>
        </div>
      </div>
    </el-dialog>
    <viewStatistics ref="viewStatisticsRef" />
  </basic-container>
</template>

<script setup>
import QRCode from 'qrcode';
import viewStatistics from './components/viewStatisticsMenu/viewStatistics.vue';
import { getList, getDetail, add, update, remove, groupListOfTrial } from '@/api/trial/trial';
import option from '@/option/trial/trial';
import { useStore } from 'vuex';
import { exportBlob } from '@/api/common';
import { getToken } from '@/utils/auth';
import { downloadXls } from '@/utils/util';
import { dateNow } from '@/utils/date';
import NProgress from 'nprogress';
import 'nprogress/nprogress.css';
import website from '@/config/website';
import { findObject } from '@smallwei/avue';
import { ref, reactive, computed, onMounted,nextTick } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useRouter } from 'vue-router';
import { change } from '@/api/job/jobinfo';
const router = useRouter();
const crud = ref(null);
const store = useStore();
const form = ref({});
const query = ref({});
const search = ref({});
let loading = ref(false);
const page = ref({
  pageSize: 10,
  currentPage: 1,
  total: 0,
});
const selectionList = ref([]);
const options = ref(option);
const data = ref([]);

let isQRCode = ref(false);
let groupOption = ref([]);
let patternOption = ref([
  {
    label: '患者',
    value: '1',
  },
  {
    label: '匿名',
    value: '2',
  },
  // {
  //   label: '医生',
  //   value: '3',
  // },
]);
let QRCodeForm = ref({
  groupValue: '',
  patternValue: '2',
  checkCode: '232145',
});
let clickMneuVal = ref({});
let viewStatisticsRef = ref(null);
let QRCodeUrl = ref('');
// permissionList 计算属性
const permission = computed(() => store.getters.permission);
const userInfo = computed(() => store.getters.userInfo);
const validData = (value, defaultVal = false) => (value ? true : defaultVal);
const permissionList = computed(() => ({
  addBtn: validData(permission.value.illness_add, false),
  viewBtn: validData(permission.value.illness_view, false),
  delBtn: validData(permission.value.illness_delete, false),
  editBtn: validData(permission.value.illness_edit, false),
}));

// ids 计算属性
const ids = computed(() => {
  return selectionList.value.map(ele => ele.id).join(',');
});
// 操作按钮点击
/* type 1新增 2查看 3新建码 4入组采集 5查看统计
   row 新增时为空 编辑时为当前行数据 详情时为当前行数据
*/
const handleMenu = (type, row = {}, index) => {
  clickMneuVal.value = row;
  let queryList = {
    // 1: {
    //   selectTab: 1,
    //   title: '新增业务管理',
    // },
    2: {
      selectTab: 1,
      trialId: `${row.id}`,
    },
    4:{
      selectTab:5,
      trialId: `${row.id}`
    },
  };
  if (queryList[type]) {
    router.push({
      path: '/trial/menu',
      query: queryList[type],
    });
  }
  if(type === 1){
    crud.value.rowAdd();
  }
  if (type === 3) {
    isQRCode.value = true;
    initData(row);
  }
  if(type === 5){
    nextTick(() => {
      viewStatisticsRef.value.open(row)
    })
  }
};
const initData = row => {
  groupListOfTrial(row.id).then(res => {
    let DATA = res.data.data;
    groupOption.value = res.data.data;
    QRCodeForm.value.groupValue = DATA[0].id;
    QRCodeUrl.value =
      window.location.origin +
      '/CrfH5?trialId=' +
      row.id +
      '&groupId=' +
      QRCodeForm.value.groupValue +
      '&patternValue=' +
      QRCodeForm.value.patternValue;
    console.log(QRCodeUrl.value);
    generateQRCode(clickMneuVal.value.id, QRCodeForm.value.groupValue);
  });
};
const changeQRCodeSelect = () => {
  console.log(QRCodeForm.value.patternValue);
  QRCodeUrl.value =
    window.location.origin +
    '/CrfH5?trialId=' +
    clickMneuVal.value.id +
    '&groupId=' +
    QRCodeForm.value.groupValue +
  '&patternValue=' + QRCodeForm.value.patternValue;
  generateQRCode(clickMneuVal.value.id, QRCodeForm.value.groupValue);
};
const generateQRCode = (trialId, groupId) => {
  // 获取二维码元素
  // 获取二维码元素，确保是一个 canvas 元素
  const canvasElement = document.getElementById('qrcode');

  // 使用 qrcode.js 生成二维码
  QRCode.toCanvas(
    canvasElement,
    QRCodeUrl.value,
    {
      width: 256,
      height: 256,
      colorDark: '#000000',
      colorLight: '#ffffff',
    },
    error => {
      if (error) {
        console.error(error);
      } else {
        console.log('二维码生成成功！');
      }
    }
  );
};
// 复制链接
const handleCopyQRCodeUrl = () => {
  const text = QRCodeUrl.value;
  const textarea = document.createElement("textarea");
  textarea.value = text;
  textarea.style.position = "absolute";
  textarea.style.opacity = "0";
  document.body.appendChild(textarea);
  textarea.select();
  document.execCommand("copy");
  document.body.removeChild(textarea);
  ElMessage.success('复制成功!');
}
const rowSave = (row, done, loading) => {
  if (row.dsfInspector instanceof Array) {
    row.dsfInspector = row.dsfInspector.join(',');
  }
  if (row.dsfSupervisor instanceof Array) {
    row.dsfSupervisor = row.dsfSupervisor.join(',');
  }
  if (row.inspector instanceof Array) {
    row.inspector = row.inspector.join(',');
  }
  if (row.researcher instanceof Array) {
    row.researcher = row.researcher.join(',');
  }
  if (row.supervisor instanceof Array) {
    row.supervisor = row.supervisor.join(',');
  }
  add(row)
    .then(() => {
      onLoad(page.value);
      ElMessage.success('操作成功!');
      done();
    })
    .catch(error => {
      loading();
      window.console.console.log(error);
    });
};

const rowUpdate = (row, index, done, loading) => {
  update(row)
    .then(() => {
      onLoad(page.value);
      ElMessage.success('操作成功!');
      done();
    })
    .catch(error => {
      loading();
      window.console.console.log(error);
    });
};

const rowDel = row => {
  ElMessageBox.confirm('确定将选择数据删除?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      return remove(row.id);
    })
    .then(() => {
      onLoad(page.value);
      ElMessage.success('操作成功!');
    });
};

const handleDelete = () => {
  if (selectionList.value.length === 0) {
    ElMessage.warning('请选择至少一条数据');
    return;
  }
  ElMessageBox.confirm('确定将选择数据删除?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      return remove(ids.value);
    })
    .then(() => {
      onLoad(page.value);
      ElMessage.success('操作成功!');
    });
};

const handleExport = () => {
  const downloadUrl = `/blade-trial/trial/export-trial?${website.tokenHeader}=${getToken()}`;
  const { name } = query.value;
  let values = {
    name_: name,
  };

  ElMessageBox.confirm('是否导出数据?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    NProgress.start();
    exportBlob(downloadUrl, values).then(res => {
      downloadXls(res.data, `疾病管理${dateNow()}.xlsx`);
      NProgress.done();
    });
  });
};

const beforeOpen = (done, type) => {
  if (['add'].includes(type)) {
    const createUser = findObject(options.value.column, 'createUser');
    createUser.value = userInfo.value.user_id;
  }
  if (['edit', 'view'].includes(type)) {
    getDetail(form.value.id).then(res => {
      form.value = res.data.data;
    });
  }
  done();
};

const searchReset = () => {
  query.value = {};
  onLoad(page.value);
};

const searchChange = (params, done) => {
  query.value = params;
  page.value.currentPage = 1;
  onLoad(page.value, params);
  done();
};

const selectionChange = list => {
  selectionList.value = list;
};

const selectionClear = () => {
  selectionList.value = [];
  crud.value.toggleSelection();
};

const currentChange = currentPage => {
  page.value.currentPage = currentPage;
};

const sizeChange = pageSize => {
  page.value.pageSize = pageSize;
};

const refreshChange = () => {
  onLoad(page.value, query.value);
};

const onLoad = (page, params) => {
  loading.value = true;
  let values = {
    descs: 'create_time',
    ...params,
  };
  getList(page.currentPage, page.pageSize, values).then(res => {
    const DATA = res.data.data;
    page.total = DATA.total;
    data.value = DATA.records;
    loading.value = false;
    selectionClear();
  });
};
</script>

<style scoped>
.QR-code-content {
  width: 100%;
  height: auto;
}
.QR-code-corm {
  width: 100%;
  height: 50px;
  margin-bottom: 12px;
}
.QR-code-img {
  width: 100%;
  display: 200px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}
.QR-code-bottom {
  width: 100%;
  height: 50px;
  margin-top: 12px;
  border-top: 1px solid #f4f4f4;
  display: flex;
  align-items: center;
}
.QR-code-dialog-body{
  overflow: hidden;
}
</style>
